package com.zhenai.rocyuan.modules.threadupdown.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.zhenai.rocyuan.modules.threadupdown.BaseSocket;
import com.zhenai.rocyuan.modules.threadupdown.BaseSocketTool;
import com.zhenai.rocyuan.modules.threadupdown.Operation;
import com.zhenai.rocyuan.modules.threadupdown.Users;
import com.zhenai.rocyuan.modules.threadupdown.Utils;

public class HandelMain implements Runnable {
	private static List<Socket> pool = new LinkedList<Socket>();
	private Socket client;
	private static final Logger log = Logger.getLogger(HandelMain.class);

	public HandelMain() {
	}

	/**
	 * 客户请求时服务器对连接池的处理
	 * 
	 * @param socket
	 */
	public static void processRequest(Socket socket) {
		synchronized (pool) {
			pool.add(pool.size(), socket);
			pool.notifyAll();
		}
	}

	@Override
	public void run() {
		System.out.println("run.....");
		while (true) {
			synchronized (pool) {
				while (pool.isEmpty()) {
					try {
						pool.wait();
					} catch (InterruptedException e) {
						log.error(e, e);
					}
				}
				client = pool.remove(0);
			}
			mainWork();
		}
	}

	/**
	 * 服务器处理连接的主要处理过程
	 */
	private void mainWork() {
		log.error(Thread.currentThread().getName());

		ObjectOutputStream objOut = null;
		ObjectInputStream objIn = null;
		Operation opera = null;
		try {
			SocketAddress address = client.getRemoteSocketAddress();
			log.debug("+++已连接[ " + address + " ].....");

			objOut = new ObjectOutputStream(client.getOutputStream());
			objIn = new ObjectInputStream(client.getInputStream());

			String ip = this.getClientIp(address);
			// 验证客户端ip
			boolean flag = this.validateIp(ip);
			objOut.writeBoolean(flag);
			objOut.flush();

			if (flag) {
				Object o = objIn.readObject();
				Users user = null;
				boolean temp = false;
				if (objIn != null && o != null && o instanceof Users) {
					user = (Users) o;
					if (Utils.validateUser(user)) {
						temp = true;
					}
				}
				// 服务器端返回验证结果
				objOut.writeBoolean(temp);
				objOut.flush();

				if (temp) {
					Object object = objIn.readObject();
					if (object instanceof Operation) {
						opera = (Operation) object;
						BaseSocketTool tool = new BaseSocketTool();
						opera = tool.todo(opera, objOut, objIn);
						System.out.println("服务器端写入对象");
						tool.writeObject(objOut, opera);
					}
				}
			}
		} catch (Exception e) {
			log.error(e, e);
		} finally {
			try {
				if (objOut != null) {
					objOut.close();
				}
				if (objIn != null) {
					objIn.close();
				}
				if (client != null) {
					client.close();
				}
			} catch (IOException e) {
				log.error(e, e);
			}
		}
	}

	/**
	 * 从0.0.0.0:1234 中获取ip
	 * 
	 * @param s
	 * @return
	 */
	public String getClientIp(SocketAddress s) {
		String ips = s.toString();
		ips = ips.replaceFirst("/", "");
		ips = ips.substring(0, ips.indexOf(":"));
		return ips;
	}

	private boolean validateIp(String ip) {
		if (BaseSocket.IP_LIMIT) {
			String[] allowips = BaseSocket.ALLOW_IPS;
			for (String s : allowips) {
				if (s.equals(ip) || s == ip) {
					return true;
				}
			}
			return false;
		} else {
			return true;
		}
	}

}
